<script setup lang="ts">
import { createRentAPI, getEnterpriseListAPI, getRentBuildListAPI, uploadAPI } from '@/apis/enterprise';
import type { Enterprise, EnterpriseListData, EnterpriseListParams } from '@/types/enterprise';
import { ElMessage, type FormInstance, type FormRules, type UploadInstance, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';

const querryParams = reactive<EnterpriseListParams>({
  name: '',
  page: 1,
  pageSize: 10
})
const getEnterpriseList = async () => {
  const res = await getEnterpriseListAPI(querryParams)
  enterpriseList.value = res.data.rows
  totalCount.value = res.data.total
  //  console.log(res);
}
//搜索
const doSearch = () => {
  querryParams.page = 1
  getEnterpriseList()
}
//弹窗组件
const dialogVisible = ref(false);
onMounted(() => {
  getEnterpriseList()
})
// 添加合同
const addRent = async (id: string) => {
  dialogVisible.value = true;
  // 获取可租赁楼宇列表
  const res = await getRentBuildListAPI();
  buildList.value = res.data;
  // 把企业 id 添加到 合同表单中
  rentForm.enterpriseId = id;
};
// 添加合同表单
const rentForm = reactive({
  buildingId: "", // 楼宇id
  contractId: "", // 合同id
  contractUrl: "", // 合同Url
  enterpriseId: "", // 企业名称
  type: 0, // 合同类型
  rentTime: [], // 合同时间
});
// 可租赁楼宇列表
const buildList = ref<{ id: string; name: string }[]>([]);
// 合同表单校验
const rentRules = ref<FormRules<typeof rentForm>>({
  buildingId: [{ required: true, message: "请选择楼宇", trigger: "change" }],
  rentTime: [{ required: true, message: "请选择租赁日期", trigger: "change" }],
  contractId: [{ required: true, message: "请上传合同文件" }],
});
// 合同表单统一校验用的实例
const addFormRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();
  const onClose = () => {
  // 关闭对话框
  dialogVisible.value = false;
  // 重置表单
  addFormRef.value?.resetFields();
  // 清空上传组件的文件信息
  uploadRef.value?.clearFiles();
  // 清空合同信息
  rentForm.contractUrl = "";
  rentForm.contractId = "";
};
// 提交合同表单
const onSubmitRent = async () => {
  try {
    await addFormRef.value?.validate();
     // 提交表单
     await createRentAPI({
      buildingId: rentForm.buildingId,
      startTime: rentForm.rentTime[0],
      endTime: rentForm.rentTime[1],
      contractUrl: rentForm.contractUrl,
      contractId: rentForm.contractId,
      type: rentForm.type,
      enterpriseId: rentForm.enterpriseId,
    });
    // 轻提示
    ElMessage.success("添加合同成功");
    // 关闭对话框，需要重置表单和上传组件
    onClose();
  } catch (error) {
    ElMessage.error("请填写完整信息");
  }
};
// 上传前校验
const beforeUpload = (rawFile: UploadRawFile) => {
  // 大小限制：5M
  const size5M = 5 * 1024 * 1024;
  // 格式限制：.png .jpg .jpeg
  const AcceptType = ["application/msword", "application/pdf"];
  if (rawFile.size > size5M) {
    ElMessage.error("文件大小不能超过5M");
    return false;
  } else if (AcceptType.includes(rawFile.type) === false) {
    ElMessage.error("仅支持扩展名为 .pdf, .doc 的合同");
    return false;
  }
};
// 删除了文件
const onFileRemove = () => {
  // 清空合同信息
  rentForm.contractId = "";
  rentForm.contractUrl = "";
};
// 上传合同
const uploadHttpRequest = async (options: UploadRequestOptions) => {
  // 准备 fromData 请求体参数(前端上传文件需要用 formData 处理成二进制数据上传)
  const formData = new FormData();
  formData.append("file", options.file);
  formData.append("type", "contract");
  // 上传租赁合同
  const res = await uploadAPI(formData);
  console.log("上传合同成功", res);
  // 保存租赁合同 id 和 url
  rentForm.contractId = res.data.id;
  rentForm.contractUrl = res.data.url;
};
const enterpriseList = ref<Enterprise[]>([])
const totalCount = ref(0)
</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="querryParams.name" @clear="doSearch" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="enterpriseList">
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button size="small" type="text" @click="addRent(row.id)">添加合同</el-button>
            <el-button size="small" type="text">查看</el-button>
            <el-button size="small" type="text">编辑</el-button>
            <el-button size="small" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination :total="totalCount" v-model:page-size="querryParams.pageSize"
        v-model:current-page="querryParams.page" :page-sizes="[2, 5, 10, 20]" @current-change="getEnterpriseList"
        @size-change="getEnterpriseList" layout="total, prev, pager, next,sizes,jumper" />
    </div>
  </div>
  <el-dialog title="添加合同" width="600px" v-model="dialogVisible">
    <div class="form-container">
      <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-model="rentForm.buildingId" placeholder="请选择">
            <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="rentTime">
          <el-date-picker v-model="rentForm.rentTime" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-dd" />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractId">
          <el-upload action="#" accept=".pdf, .doc, .docx" :http-request="uploadHttpRequest"
            :before-upload="beforeUpload" :on-remove="onFileRemove">
            <el-button size="small" type="primary" plain>
              上传合同文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持扩展名：.doc .pdf, 文件大小不超过5M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button  @close="onClose" @click="dialogVisible = false">取 消</el-button>
        <el-button @click="onSubmitRent" type="primary">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
